const path = require("path");
const prettyBytes = require("pretty-bytes");
const chalk = require("chalk");
// The build folder is ready to be deployed.
class BuildTipsPlugin {
  apply(compiler) {
    let assets;
    compiler.hooks.compilation.tap("BuildTipsPlugin", (p1, p2) => {
      assets = [];
    });
    compiler.hooks.assetEmitted.tap(
      "BuildTipsPlugin",
      (file, { content, targetPath }) => {
        assets.push({
          path: path.relative(compiler.context, targetPath),
          size: prettyBytes(content.length),
        });
      }
    );

    compiler.hooks.done.tapAsync("BuildTipsPlugin", (stats) => {
      let outputDir = path.relative(
        compiler.context,
        stats.compilation.options.output.path
      );
      setTimeout(() => {
        console.log(
          "\n",
          chalk.green(assets.map((i) => `${i.size} \t ${i.path}`).join("\n"))
        );
        console.log(chalk.green(`\n${outputDir} 文件夹准备好了\n`));
        if (stats.compilation.options.output.publicPath.length > 2) {
          // 当配置homepage时提示
          console.log(
            `\n当前你的homepage被设置为发布在${chalk.green(
              stats.compilation.options.output.publicPath
            )}路径下。`
          );
          console.log(
            `你通过 package.json 文件的 ${chalk.green(
              "homepage"
            )}字段控制此项。\n`
          );
        } else {
          // 当项目没有配置homepage时，提示运行方法
          console.log(
            `\n您可以运行 ${chalk.green(`serve ./${outputDir}`)} 部署项目\n`
          );
        }
      }, 200);
    });
  }
}

module.exports = BuildTipsPlugin;
